package com.bac.rentmap.web.controller.ad.details;

import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.bac.rentmap.ad.flat.FlatAd;
import com.bac.rentmap.ad.flat.FlatAdDao;
import com.bac.rentmap.ad.flat.rating.FlatAdRatingCalculator;
import com.bac.rentmap.web.util.PathVariableParser;

public class FlatAdDetailsController extends AbstractController implements BeanNameAware {
    private FlatAdDao flatAdDao;
    private FlatAdRatingCalculator flatAdRatingCalculator;
    private Pattern pattern;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView res;
        List<String> pathVariables = PathVariableParser.getPathVariables(request.getServletPath(), pattern);
        Long flatAdId = Long.valueOf(pathVariables.get(0));
        FlatAd flatAd = flatAdDao.get(flatAdId);
        if(flatAd != null){
            res = new ModelAndView("ad/details/view");
            res.addObject("flatAd", flatAd);
            long rating = flatAdRatingCalculator.calculateRating(flatAd);
            res.addObject("normalizedRating", flatAdRatingCalculator.normalizeRating(rating));
        }
        else{
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            res = new ModelAndView("ad/details/message");
        }
        return res;
    }

    @Required
    public void setFlatAdDao(FlatAdDao flatAdDao) {
        this.flatAdDao = flatAdDao;
    }

    @Required
    public void setFlatAdRatingCalculator(
            FlatAdRatingCalculator flatAdRatingCalculator) {
        this.flatAdRatingCalculator = flatAdRatingCalculator;
    }
    
    public void setBeanName(String beanName) {
        pattern = PathVariableParser.createPattern(beanName);
    }
}
